package com.weaver.seconddev.custom.qc1853114.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.authority.annotation.WeaPermission;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.eteams.file.client.remote.FileClientService;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.seconddev.custom.qc1853114.service.ContractService;
import com.weaver.teams.security.context.UserContext;
import com.weaver.teams.security.user.User;
import com.weaver.verupgrade.general.MD5;
import com.weaver.verupgrade.general.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;


/**
 * api 需要用户会话，e10 入口地址访问
 * papi 任何人都可以直接访问 public api，e10入口地址访问
 * sapi 服务内部通信的接口路由前缀 /sapi/secondev，e10入口地址访问不了，可用于发布开放平台接口
 * 二开服务接口前缀规范：/api/secondev，/papi/secondev，/sapi/secondev
 */
@RestController
@RequestMapping("/api/secondev/qc1853114/contract")
@WeaPermission(publicPermission = true)
public class ApiController {

    static String CONF = "contract_compare";

    @Autowired
    ContractService contractService;

    @Autowired
    private FileDownloadService fileDownloadService;

    @Autowired
    private FileClientService fileClientService;

    private static final Logger log = LoggerFactory.getLogger(ApiController.class);

    /**
     * 二开接口的返回值统一用WeaResult封装
     *
     * @param key
     * @return WeaResult<String>
     */
    @GetMapping("/hello")
    public WeaResult<String> hello(@RequestParam("key") String key) {
        // 获取当前用户信息
        final User currentUser = UserContext.getCurrentUser();
        // 用户id
        final Long employeeId = currentUser.getEmployeeId();
        // 租户key
        final String tenantKey = currentUser.getTenantKey();
        log.info("params is {}", key);
        try {
            // todo api
            log.error("currentUser ", currentUser);
            log.error("employeeId ", employeeId);
            log.error("tenantKey ", tenantKey);
        } catch (Exception e) {
            log.error("error ", e);
        }
        return WeaResult.success(key);
    }


    @GetMapping("/getDocField")
    public WeaResult<String> getDocField(@RequestParam("workflowid") String workflowid,@RequestParam( value = "browserType",defaultValue = "htlx") String browserType,@RequestParam(value = "dbFieldName",defaultValue = "scfj") String dbFieldName) {
        Map<String, Object> res = null;
        try {
//            String browserType = "htlx";
//            String dbFieldName = "fjsc";

            log.error("ApiController---getDocField---workflowid==" + workflowid + "---browserType==" + browserType + "---dbFieldName==" + dbFieldName);
            res = contractService.getDetailDocField(workflowid, browserType, dbFieldName);
            log.error("res is {}", JSONObject.toJSON(res));
        } catch (Exception e) {

            log.error("getDocField--Exception--e==" + e);

        }
        return WeaResult.success(JSON.toJSONString(res));
    }


    /**
     * 将服务器文件上传至睿真服务器
     * @param leftEntryIds
     * @param rightEntryIds
     * @return
     */
    @GetMapping("/compareTest")
    public WeaResult<String> compareTest(@RequestParam("leftEntryIds") String leftEntryIds, @RequestParam("rightEntryIds") String rightEntryIds) {
        Map<String, Object> returnMap = new HashMap<>();

        try {
            log.error("compareTest---进来了");
            RestTemplate restTemplate = new RestTemplate();
            URI uri = new URI("https://regenai.glority.cn/v1/comparision/docs/upload");
            //如果发送的参数数据是json数据的话，需要添加特殊的请求头
            HttpHeaders headers = new HttpHeaders();

            long timestamp = System.currentTimeMillis() / 1000;

            headers.add("Cookie", "langType=zh_CN; langType=zh_CN; ETEAMS_TGC=TGT1004-O451MDG15D6czoRQmL5DCeW9ve5JexoJHT5uhAbMWdUwwxEZ0o; ETEAMSID=PCACCOUNT_b251e4126be56969bd5c6d682a0423ae-C3D94NDJB31KD; ETEAMSID=PCACCOUNT_b251e4126be56969bd5c6d682a0423ae-C3D94NDJB31KD; acw_tc=0a47308f17552381680032324eccd2c47d275c4c1aa416555b3629d2fd3d89; JSESSIONID=9F551035C98E4DF20F432E258FB270AC");
            headers.add("Content-Type", "multipart/form-data");  // 关键：设置multipart类型
            //添加参数,因为HttpEntity里面的参数是MultiValueMap类型的，所以使用这个map集合
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            String tokensss = getToken(timestamp);

            log.error("compareTest---tokensss==" + tokensss);

            map.add("app_key", "623abda6");
            map.add("token", tokensss);
            map.add("timestamp", String.valueOf(timestamp));

            Map<String, String> leftFilePath = getFilePath(leftEntryIds);
            map.add("left_file_url", leftFilePath.get("filePath"));
            map.add("left_filename", leftFilePath.get("fileUrl"));

            Map<String, String> rightFilePath = getFilePath(rightEntryIds);
            map.add("right_file_url", rightFilePath.get("filePath"));
            map.add("right_filename", rightFilePath.get("fileUrl"));

            log.error("compareTest---map==" + JSONObject.toJSONString(map));


            //添加请求的实体类，这里第一个参数是要发送的参数，第二个参数是请求头里的数据
            HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers);

            ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class);
            //把字符串转换为json
            JSONObject jsonObject = JSON.parseObject(exchange.getBody());

            returnMap.put("data",jsonObject);

            log.error("compareTest---结束了");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            log.error("compareTest---Exception--==" + e);
        }

        return WeaResult.success(JSONObject.toJSONString(returnMap));
    }


    @GetMapping("/compareResultTest")
    public WeaResult<String> compareResultTest(@RequestParam("project_id") String project_id) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            log.error("compareResultTest---进来了");

            long timestamp = System.currentTimeMillis() / 1000;
            String tokensss = getToken(timestamp, project_id);

            log.error("compareResultTest---tokensss==" + tokensss);

            returnMap.put("app_key", "623abda6");
            returnMap.put("token", tokensss);
            returnMap.put("timestamp", String.valueOf(timestamp));
            returnMap.put("project_id", project_id);
            returnMap.put("sign_keys", "project_id");

            log.error("compareResultTest---map==" + JSONObject.toJSONString(returnMap));
            log.error("compareResultTest---结束了");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("compareResultTest---Exception--==" + e);
        }
        return WeaResult.success(JSONObject.toJSONString(returnMap));
    }

    public static String getToken(long timestamp, String project_id) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("623abda6");
        buffer.append("+");
        buffer.append(timestamp);
        buffer.append("+");
        buffer.append("2279fa65026b6ff6f03dd8efbae6d044");
        if (!"".equals(project_id)) {
            buffer.append("+");
            buffer.append(project_id);
        }
        MD5 md5 = new MD5();
        return md5.getMD5ofStr(buffer.toString()).toLowerCase();
    }

    public static String getToken(long timestamp) {
        return getToken(timestamp, "");
    }

    public Map<String, String> getFilePath(String fileId) {
        log.error("compareTest---getDocPath---进来了---fileId==" + fileId);
        Map<String, String> fileMap = new HashMap<>();

        if ("".equals(fileId)) {
            return fileMap;
        }
        FileData fileData = fileDownloadService.downloadFile(Long.valueOf(fileId));

        String filePath = fileData.getLoadUrl();
        String fileUrl = "11";

        // 通过附件fileId获取FileObj对象
        FileObj fileObj = fileClientService.getById(Long.valueOf(fileId));
        String fileName = fileObj.getName(); // 直接获取附件名称


        fileMap.put("filePath", filePath);
        fileMap.put("fileUrl", fileName);
        log.error("compareTest---getDocPath---stringObjectMap==" + JSONObject.toJSONString(fileMap));
        log.error("compareTest---getDocPath---结束了");
        return fileMap;

    }


}